package net.huashitong.oversee.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.oversee.dao.ScoreSummaryDao;
import net.huashitong.oversee.databean.DepartRank;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.ScoreSummary;
import net.huashitong.oversee.entity.ScoreSummaryTemp;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import net.huashitong.taskGroup.entity.JobGroup;
import net.huashitong.taskGroup.service.JobGroupService;
import net.huashitong.user.dao.BnpUserDao;
import net.huashitong.user.entity.BnpUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static net.huashitong.utils.UtilsTools.getCurrentDateTime1;

@Service
public class ScoreSummaryService extends StringPKService<ScoreSummary> {

    @Autowired
    private ScoreSummaryDao dao;

    @Autowired
    private BnpUserDao userDao;

    @Autowired
    private GradePointService gradePointService;

    @Autowired
    private JobGroupService jobGroupService;

    @Autowired
    private SysTableService tableService;

    @Autowired
    private ScoreSummaryTempService tempService;

    @Autowired
    private NodeScoreService nodeScoreService;

    @Override
    protected BaseDao<ScoreSummary, String> getDao() {
        return dao;
    }

    @Override
    protected void beforeSave(ScoreSummary obj) {
        obj.setSysId(tableService.updateMaxSysId("t_scoresummary", null));
    }


    public List<ScoreSummary> queryByFilter(ScoreSummaryFilter filter) {
        return dao.queryByFilter(filter);
    }

    public List<ScoreSummary> queryByFilterNoPage(ScoreSummaryFilter filter) {
        return dao.queryByFilterNoPage(filter);
    }

    /**
     * 汇总得分
     */
    public void updateSummaryScore() {
        List<ScoreSummary> resultList = new ArrayList<>();
        List<ScoreSummary> resultList1 = new ArrayList<>();
        List<ScoreSummary> resultList2 = new ArrayList<>();
        List<ScoreSummary> resultList3 = new ArrayList<>();
        List<ScoreSummary> oldScoreSummary = query();
        //绩效得分
        Map<String, Double> userScoreMap = new HashMap<>();
        //绩效考核次数
        Map<String, Integer> userCountMap = new HashMap<>();

        //攻坚任务
        Map<String, Double> userScoreGJMap = new HashMap<>();
        Map<String, Integer> userCountGJMap = new HashMap<>();

        //查询所有督查组
        List<JobGroup> jobGroups = jobGroupService.query();
        //封装督查组map
        Map<String, JobGroup> jobGroupMap = new HashMap<>();

        for (JobGroup jobGroup : jobGroups) {
            if (!jobGroupMap.containsKey(jobGroup.getGroupCode())) {
                jobGroupMap.put(jobGroup.getGroupCode(), jobGroup);
            }
        }
        //所有绩效评分情况（已完成、已考核的绩效评分）,关联督查任务
        List<GradePoint> gradePoints = gradePointService.queryChecked();
        List<GradePoint> successfulGradePoints = gradePointService.querySuccessfulGradePoint();
        gradePoints.addAll(successfulGradePoints);
        for (GradePoint g : gradePoints) {
            if ("攻坚任务".equals(g.getCheckType())) {
                //攻坚任务绩效得分处理
                if (!userScoreGJMap.containsKey(g.getCheckObjectId())) {
                    Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                    userScoreGJMap.put(g.getCheckObjectId(), score);
                    userCountGJMap.put(g.getCheckObjectId(), 1);
                } else {
                    Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                    Double newScore = userScoreGJMap.get(g.getCheckObjectId()) + score;
                    userScoreGJMap.put(g.getCheckObjectId(), newScore);
                    int count = userCountGJMap.get(g.getCheckObjectId());
                    count++;
                    userCountGJMap.put(g.getCheckObjectId(), count);
                }
            }

            if (!userScoreMap.containsKey(g.getCheckObjectId())) {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                userScoreMap.put(g.getCheckObjectId(), score);
                userCountMap.put(g.getCheckObjectId(), 1);
            } else {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                Double newScore = userScoreMap.get(g.getCheckObjectId()) + score;
                userScoreMap.put(g.getCheckObjectId(), newScore);
                int count = userCountMap.get(g.getCheckObjectId());
                count++;
                userCountMap.put(g.getCheckObjectId(), count);
            }

        }
        //查询所有用户
        List<BnpUser> users = userDao.query();
        //封装用户
        Map<String, BnpUser> userMap = new HashMap<>();
        Map<String, ScoreSummary> inspectorsMap = new HashMap<>();
        for (BnpUser u : users) {
            if (!userMap.containsKey(u.getSysId())) {
                userMap.put(u.getSysId(), u);
            }
        }
        //*************************处理非攻坚任务情况*************************
        for (Map.Entry<String, Double> entry : userScoreMap.entrySet()) {
            ScoreSummary summary = new ScoreSummary();

            String userId = entry.getKey();
            double allScore = entry.getValue();
            double resScore = 0.0;
            if (ObjectUtils.isNotBlank(userMap.get(userId))) {
                String branchType = userMap.get(userId).getBranchType();
                if("6".equals(branchType)){
                    continue;
                }
                resScore = allScore / (userCountMap.get(userId)) +
                        allScore / 10;
                summary.setCheckDept(userMap.get(userId).getBranch());
                summary.setCheckObject(userMap.get(userId).getName());
                summary.setScore(String.format("%.2f", resScore) + "");
                summary.setUserId(userMap.get(userId).getSysId());
                summary.setSummaryDate(getCurrentDateTime1());
                summary.setBranchType(userMap.get(userId).getBranchType());
            }
            if (ObjectUtils.isNotBlank(jobGroupMap.get(userId))) {
                ScoreSummary summary1 = new ScoreSummary();
                resScore = allScore / (userCountMap.get(userId)) +
                        allScore / 10;
                summary1.setCheckDept(jobGroupMap.get(userId).getGroupDuty());
                summary1.setCheckObject(jobGroupMap.get(userId).getGroupName());
                summary1.setScore(String.format("%.2f", resScore) + "");
                summary1.setUserId(jobGroupMap.get(userId).getGroupCode());
                summary1.setSummaryDate(getCurrentDateTime1());
                summary1.setBranchType("4");
                resultList1.add(summary1);
                continue;
            }
            //出现两个督查组的情况
            if (StringUtils.isBlank(summary.getScore())) {
                if (userId.contains(",")) {
                    String[] userIds = userId.split(",");
                    for (String u : userIds) {
                        ScoreSummary summary2 = new ScoreSummary();
                        resScore = allScore / (userCountMap.get(userId)) +
                                allScore / 10;
                        summary2.setCheckDept(jobGroupMap.get(u).getGroupDuty());
                        summary2.setCheckObject(jobGroupMap.get(u).getGroupName());
                        summary2.setScore(String.format("%.2f", resScore) + "");
                        summary2.setUserId(jobGroupMap.get(u).getGroupCode());
                        summary2.setSummaryDate(getCurrentDateTime1());
                        summary2.setBranchType("4");
                        resultList2.add(summary2);
                    }
                }
                continue;
            }
            resultList.add(summary);
        }
        for (ScoreSummary list1 : resultList1) {
            if (!inspectorsMap.containsKey(list1.getUserId())) {
                inspectorsMap.put(list1.getUserId(), list1);
            }
        }
        for (ScoreSummary list2 : resultList2) {
            ScoreSummary re = inspectorsMap.get(list2.getUserId());
            if (ObjectUtils.isNotBlank(re)) {
                double scoreDouble = Double.parseDouble(re.getScore()) + Double.parseDouble(list2.getScore());
                re.setScore(String.format("%.2f", scoreDouble) + "");
                inspectorsMap.put(list2.getUserId(), re);
            } else {
                resultList3.add(list2);
            }
        }
        for (Map.Entry<String, ScoreSummary> inspectors : inspectorsMap.entrySet()) {
            ScoreSummary summary = inspectors.getValue();
            resultList3.add(summary);
        }
        resultList.addAll(resultList3);
        //*************************以上是处理非攻坚任务情况*************************
        //*************************以下是处理攻坚任务情况*************************
        for (Map.Entry<String, Double> gj : userScoreGJMap.entrySet()) {
            ScoreSummary summary = new ScoreSummary();
            String userId = gj.getKey();
            double allScore = gj.getValue();
            double resScore = 0.0;
            Integer count = userCountGJMap.get(userId);
            resScore = allScore / (userCountGJMap.get(userId)) +
                    count;
            summary.setCheckDept(userMap.get(userId).getBranch());
            summary.setCheckObject(userMap.get(userId).getName());
            summary.setScore(String.format("%.2f", resScore) + "");
            summary.setUserId(userMap.get(userId).getSysId());
            summary.setSummaryDate(getCurrentDateTime1());
            summary.setBranchType("5"); //攻坚任务考核汇总
            resultList.add(summary);
        }

        batchDeleteObject(oldScoreSummary);
        batchSave(resultList);
        //更新领导得分
        List<ScoreSummary> leaderScoreSummary = nodeScoreService.updateLeaderScoreSummary();
        batchSave(leaderScoreSummary);
    }

    /**
     * 查询汇总成绩(时间段)
     */
    public void saveSummaryScoreToTemp(ScoreSummaryFilter filter) {
        List<ScoreSummary> resultList = new ArrayList<>();
        List<ScoreSummary> resultList1 = new ArrayList<>();
        List<ScoreSummary> resultList2 = new ArrayList<>();
        List<ScoreSummary> resultList3 = new ArrayList<>();
        List<ScoreSummaryTemp> oldScoreSummaryTemp = tempService.query();
        //绩效得分
        Map<String, Double> userScoreMap = new HashMap<>();
        //绩效考核次数
        Map<String, Integer> userCountMap = new HashMap<>();

        //查询所有督查组
        List<JobGroup> jobGroups = jobGroupService.query();
        //封装督查组map
        Map<String, JobGroup> jobGroupMap = new HashMap<>();

        for (JobGroup jobGroup : jobGroups) {
            if (!jobGroupMap.containsKey(jobGroup.getGroupCode())) {
                jobGroupMap.put(jobGroup.getGroupCode(), jobGroup);
            }
        }
        //所有绩效评分情况（已完成、已考核的绩效评分）,关联督查任务（时间段）
        List<GradePoint> gradePoints = gradePointService.queryCheckedInTime(filter);
        List<GradePoint> successfulGradePoints = gradePointService.querySuccessfulGradePointInTime(filter);
        gradePoints.addAll(successfulGradePoints);
        for (GradePoint g : gradePoints) {
            if (!userScoreMap.containsKey(g.getCheckObjectId())) {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                userScoreMap.put(g.getCheckObjectId(), score);
                userCountMap.put(g.getCheckObjectId(), 1);
            } else {
                Double score = Double.parseDouble(StringUtils.isBlank(g.getSoucre()) ? "0.0" : g.getSoucre());
                Double newScore = userScoreMap.get(g.getCheckObjectId()) + score;
                userScoreMap.put(g.getCheckObjectId(), newScore);
                int count = userCountMap.get(g.getCheckObjectId());
                count++;
                userCountMap.put(g.getCheckObjectId(), count);
            }
        }
        //查询所有用户
        List<BnpUser> users = userDao.query();
        //封装用户
        Map<String, BnpUser> userMap = new HashMap<>();
        Map<String, ScoreSummary> inspectorsMap = new HashMap<>();
        for (BnpUser u : users) {
            if (!userMap.containsKey(u.getSysId())) {
                userMap.put(u.getSysId(), u);
            }
        }
        for (Map.Entry<String, Double> entry : userScoreMap.entrySet()) {
            ScoreSummary summary = new ScoreSummary();

            String userId = entry.getKey();
            double allScore = entry.getValue();
            double resScore = 0.0;
            if (ObjectUtils.isNotBlank(userMap.get(userId))) {
                resScore = allScore / (userCountMap.get(userId)) +
                        allScore / 10;
                summary.setCheckDept(userMap.get(userId).getBranch());
                summary.setCheckObject(userMap.get(userId).getName());
                summary.setScore(String.format("%.2f", resScore) + "");
                summary.setUserId(userMap.get(userId).getSysId());
                summary.setSummaryDate(getCurrentDateTime1());
                summary.setBranchType(userMap.get(userId).getBranchType());
            }
            if (ObjectUtils.isNotBlank(jobGroupMap.get(userId))) {
                ScoreSummary summary1 = new ScoreSummary();
                resScore = allScore / (userCountMap.get(userId)) +
                        allScore / 10;
                summary1.setCheckDept(jobGroupMap.get(userId).getGroupDuty());
                summary1.setCheckObject(jobGroupMap.get(userId).getGroupName());
                summary1.setScore(String.format("%.2f", resScore) + "");
                summary1.setUserId(jobGroupMap.get(userId).getGroupCode());
                summary1.setSummaryDate(getCurrentDateTime1());
                summary1.setBranchType("4");
                resultList1.add(summary1);
                continue;
            }
            //出现两个督查组的情况
            if (StringUtils.isBlank(summary.getScore())) {
                String[] userIds = userId.split(",");
                for (String u : userIds) {
                    ScoreSummary summary2 = new ScoreSummary();
                    resScore = allScore / (userCountMap.get(userId)) +
                            allScore / 10;
//                    if(ObjectUtils.isNotBlank(jobGroupMap.get(u))){
//                        summary2.setCheckDept(jobGroupMap.get(u).getGroupDuty());
//                        summary2.setCheckObject(jobGroupMap.get(u).getGroupName());
//                        summary2.setUserId(jobGroupMap.get(u).getGroupCode());
//                    }
                    summary2.setCheckDept(jobGroupMap.get(u).getGroupDuty());
                    summary2.setCheckObject(jobGroupMap.get(u).getGroupName());
                    summary2.setUserId(jobGroupMap.get(u).getGroupCode());
                    summary2.setScore(String.format("%.2f", resScore) + "");
                    summary2.setSummaryDate(getCurrentDateTime1());
                    summary2.setBranchType("4");
                    resultList2.add(summary2);
                }
                continue;
            }
            resultList.add(summary);
        }

        for (ScoreSummary list1 : resultList1) {
            if (!inspectorsMap.containsKey(list1.getUserId())) {
                inspectorsMap.put(list1.getUserId(), list1);
            }
        }
        for (ScoreSummary list2 : resultList2) {
            ScoreSummary re = inspectorsMap.get(list2.getUserId());
            if (ObjectUtils.isNotBlank(re)) {
                double scoreDouble = Double.parseDouble(re.getScore()) + Double.parseDouble(list2.getScore());
                re.setScore(scoreDouble + "");
                inspectorsMap.put(list2.getUserId(), re);
            } else {
                resultList3.add(list2);
            }
        }

        for (Map.Entry<String, ScoreSummary> inspectors : inspectorsMap.entrySet()) {
            ScoreSummary summary = inspectors.getValue();
            resultList3.add(summary);
        }
        resultList.addAll(resultList3);
        //最终查询得到的结果：resultList
        resultList.addAll(resultList3);
        List<ScoreSummaryTemp> result = new ArrayList<>();
        for (ScoreSummary summary : resultList) {
            ScoreSummaryTemp t = new ScoreSummaryTemp();
            BeanUtils.copyProperties(summary, t);
            result.add(t);
        }
        tempService.batchDeleteObject(oldScoreSummaryTemp);
        tempService.batchSave(result);
    }

    public void updateSummaryScoreRank() {
        List<ScoreSummary> summaries = this.query();
        Collections.sort(summaries, new Comparator<ScoreSummary>() {
            @Override
            public int compare(ScoreSummary g1, ScoreSummary g2) {
                double score1 = Double.parseDouble(StringUtils.isBlank(g1.getScore()) ? "0" : g1.getScore());
                double score2 = Double.parseDouble(StringUtils.isBlank(g2.getScore()) ? "0" : g2.getScore());
                if (score1 < score2) {
                    return 1;
                } else if (score1 == score2) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        for (int i = 0, s = summaries.size(); i < s; i++) {
            if (i > 0 && Double.parseDouble(StringUtils.isBlank(summaries.get(i).getScore()) ? "0" : summaries.get(i).getScore())
                    == Double.parseDouble(StringUtils.isBlank(summaries.get(i - 1).getScore()) ? "0" : summaries.get(i - 1).getScore())) {
                summaries.get(i).setRank(summaries.get(i - 1).getRank());
            } else {
                summaries.get(i).setRank(i + 1 + "");
            }
        }
        this.batchUpdate(summaries);
    }

    /**
     * 更新汇总得分中分组别的排名情况（TypeRank）
     */
    public void updateSummaryScoreTypeRank() {
        ScoreSummaryFilter filter = new ScoreSummaryFilter();
        List<String> branchTypes = new ArrayList<>();
        branchTypes.add("0");
        branchTypes.add("1");
        branchTypes.add("4");
        branchTypes.add("6");
        for (String b : branchTypes) {
            filter.setBranchType(b);
            List<ScoreSummary> summaries = this.queryByFilterNoPage(filter);
            Collections.sort(summaries, new Comparator<ScoreSummary>() {
                @Override
                public int compare(ScoreSummary g1, ScoreSummary g2) {
                    double score1 = Double.parseDouble(StringUtils.isBlank(g1.getScore()) ? "0" : g1.getScore());
                    double score2 = Double.parseDouble(StringUtils.isBlank(g2.getScore()) ? "0" : g2.getScore());
                    if (score1 < score2) {
                        return 1;
                    } else if (score1 == score2) {
                        return 0;
                    } else {
                        return -1;
                    }
                }
            });
            for (int i = 0, s = summaries.size(); i < s; i++) {
                if (i > 0 && Double.parseDouble(StringUtils.isBlank(summaries.get(i).getScore()) ? "0" : summaries.get(i).getScore())
                        == Double.parseDouble(StringUtils.isBlank(summaries.get(i - 1).getScore()) ? "0" : summaries.get(i - 1).getScore())) {
                    summaries.get(i).setTypeRank(summaries.get(i - 1).getTypeRank());
                } else {
                    summaries.get(i).setTypeRank(i + 1 + "");
                }
            }
            this.batchUpdate(summaries);
        }
    }

    public List<ScoreSummary> queryScoreSummaryByIds(List<String> ids) {
        return dao.queryScoreSummaryByIds(ids);
    }

    public List<DepartRank> queryDepartRank(ScoreSummaryFilter filter) {
        return dao.queryDepartRank(filter);
    }

    public List<DepartRank> queryDepartRankNoPage(ScoreSummaryFilter filter) {
        return dao.queryDepartRankNoPage(filter);
    }

    public List<DepartRank> queryDepartRankNoPageInTime(ScoreSummaryFilter filter) {
        return dao.queryDepartRankNoPageInTime(filter);
    }
}
